const db = require("../../module/db/db.js")
const jsonParse = require('../../lib/jsonParse.js')
const axios = require("../../lib/params.js")
const jwt = require('jsonwebtoken');
const pdf = require('html-pdf');
const fs = require('fs')

// const puppeteer = require('puppeteer'); // 生成pdf

const shopCars = db.getSchema("shopCar")
const phoneInfo = require('./goodsInfo').phoneInfo
const notebookInfo = require('./goodsInfo').notebookInfo
const makeupInfo = require('./goodsInfo').makeupInfo
// console.log(WebSocketServer.web_socket_handler(), 99999)

process.on('unhandledRejection', error => {
    console.log('我帮你处理了', error.message);
})

module.exports = {
    // 清单打印
    async printPdf(request, response, handler){
        response.writeHead(200, {
            'Content-Type': 'application/octet-stream',//告诉浏览器这是一个二进制文件
        });//设置响应头
        /* 方法1 */
        let params = await axios.grabPostParams(request)
        var options = {
            "format": 'A4',
            "height": "10mm",
            "type": "pdf",  
            "header": {
                "height": "45mm",
                "contents": '<div style="text-align: center;">Author: Marc Bachmann</div>'
              },
            "footer": {
                "height": "28mm",
                "contents": {
                  default: '<span style="color: #444;">{{page}}</span>/<span>{{pages}}</span>', // fallback value
                }
              }
        }
        // pdf.create(JSON.parse(params.el), options).toFile(`E:\/privatePro\/shopCarPdf\/tests.pdf`, function(err, res) {
        //     const readStream = fs.createReadStream(res.filename).pipe(response);
        //     readStream.on('data', (chunk) => {
        //         response.write(chunk, 'binary');//文档内容以二进制的格式写到response的输出流
        //     });
        //     console.log(readStream, 9999)
        //     fs.unlink(res.filename, err => {
        //         err ? console.log(err) : console.log("delete success");
        //     })
        //     readStream.on('end', () => {
        //         response.end(readStream);
        //     })
        // });

        pdf.create(JSON.parse(params.el), options).toStream(function(err, stream){
            const readStream = fs.createReadStream(stream.path).pipe(response);
            readStream.on('data', (chunk) => {
                response.write(chunk, 'binary');//文档内容以二进制的格式写到response的输出流
            });
            // fs.unlink(res.filename, err => {
            //     err ? console.log(err) : console.log("delete success");
            // })
            readStream.on('end', () => {
                response.end(readStream);
            })
        });
        

        /* 方法2 */
        // const browser = await puppeteer.launch()
        // const page = await browser.newPage()
        // await page.goto('http://localhost:8006/#/shopCar', { waitUntil: 'networkidle2' })
        // await page.pdf({path: 'test1.pdf', format: 'a4'})
        // await browser.close()
        // await jsonParse.sendResult(response, 200, '添加成功', )
    },
    // 加入购物车
    async addGoodsToCar(request, response, handler) {
        let token = request.headers['x-token'].replace('dj', '');
        const decodeResult = jwt.decode(token)
        let userName = decodeResult.userName
        if (userName) {
            let param = await axios.grabPostParams(request)
            shopCars.find({
                userName: userName,
                goodsCode: param.goodsCode
            }).exec(function (err, data) {
                if (data.length) {
                    let temp = JSON.parse(JSON.stringify(data))
                    console.log(temp[0].limitNum)
                    if(temp[0].limitNum && temp[0].goodsNum + 1 > temp[0].limitNum) {
                        // jsonParse.sendResult(0, '添加失败,已超过最后限购数量' )
                        jsonParse.sendResult(response, 0, '添加失败,已超过最后限购数量' )
                        return
                    }
                    shopCars.updateOne({
                        userName: userName,
                        goodsCode: param.goodsCode
                    }, {
                        $set: {
                            goodsNum: temp[0].goodsNum + 1
                        }
                    }).exec(function(err, da){
                        if (err) {
                            jsonParse.sendResult(response, 0, '添加失败', )
                        } else {
                            jsonParse.sendResult(response, 200, '添加成功' )
                        }
                    })
                    
                } else {
                    let dbFn = phoneInfo
                    if(param.type == 1) {
                        dbFn = phoneInfo
                    } else if(param.type == 2) {
                        dbFn = notebookInfo
                    } else if(param.type == 3) {
                        dbFn = makeupInfo
                    }
                    dbFn.find({
                        goodsCode: param.goodsCode
                    }).select({
                        _id: 0
                    }).exec(function (err, data) {
                        let temp = JSON.parse(JSON.stringify(data))
                        let obj = {
                            userName: userName,
                            date: new Date().getTime(),
                            goodsNum: 1,
                            ...temp[0]
                        }
                        let shopCar = new shopCars(obj)
                        shopCar.save(function (err, data) {
                            if (err) {
                                jsonParse.sendResult(0, '添加失败', )
                            } else {
                                jsonParse.sendResult(response, 200, '添加成功', )
                            }
                        })
                    })
                }
            })
        } else {
            jsonParse.sendResult(response, 0, '未登录', )
        }
    },
    // 更新购物车数量
    async updateShopCar(request, response, userName){
        let param = await axios.grabPostParams(request)
        shopCars.updateOne({
            userName: userName,
            goodsCode: param.goodsCode
        }, {
            $set: {
                goodsNum: param.goodsNum
            }
        }).exec(function(err, da){
            if (err) {
                jsonParse.sendResult(0, '添加失败', )
            } else {
                jsonParse.sendResult(response, 200, '更新成功', )
            }
        })
    },
    // 购物车删除
    async deleteShopCar(request, response, userName){
        let param = await axios.grabPostParams(request)
        shopCars.deleteOne({
            userName: userName,
            goodsCode: param.goodsCode
        }).exec(function(err, da){
            if (err) {
                jsonParse.sendResult(0, '删除失败', )
            } else {
                jsonParse.sendResult(response, 200, '删除成功', )
            }
        })
    },
    // 批量删除
    async deleteShopCarMany(request, response, userName){
        let param = await axios.grabPostParams(request)
        await shopCars.deleteMany({goodsCode:{$in:param.list}, userName: userName}).exec(function() {
            jsonParse.sendResult(response, 200, '删除成功')
        })
    },
    // 购物车数量
    async getGoodsCarNum(request, response, userName) {
        let param = await axios.grabPostParams(request)
        let data = {
            userName: userName
        }
        if(param.goodsCode){
            data.goodsCode = param.goodsCode
        }
        shopCars.find(data, { goodsNum: 1 }).exec(function (err, data) {
            let total = 0
            data.forEach(e => {
                total += e.goodsNum
            })
            jsonParse.sendResult(response, 200, total, '查询成功')
        })
    },
    // 购物车明细
    async getGoodsCarDetail(request, response, userName) {
        shopCars.find({
            userName: userName,
        }).select({
            userName: 0
        }).exec(function (err, data) {
            if (data) {
                jsonParse.sendResult(response, 200, data, '查询成功')
            } else {

            }
        })
    }
}